<template>
    <div class="page">

        <a-steps :current="current">
            <a-step v-for="item in steps" :key="item.title" :title="item.title" :description="item.description" />
        </a-steps>

        <div class="steps-content">
            <a-row type="flex" style="width:100%;">
                <a-col :span="8" style="text-align: left;">
                    <a-button size="large" @click="prev" :disabled="current == 0">
                        <left-outlined />
                    </a-button>  
                </a-col>
                <a-col :span="8" style="text-align: center;">
                    <div v-show="current == 0">
                        <a-form-item label="站号" >
                            <a-select size="large" v-model:value="station" style="width: 100px;text-align: center;">
                                <a-select-option :value="i" v-for="i in 255" :key="i">{{ i }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </div>
                    <div v-show="current == 1">
                        <a-button size="large" type="primary" @click="ADreset">AD值重置</a-button>
                    </div>
                    <div v-show="current == 2">
                        <a-button size="large" type="primary" @click="zeroPoint">零点校准</a-button>
                    </div>
                    <div v-show="current == 3">
                        <a-input size="large" style="text-align: center;" v-model:value="famar">
                            <template #addonBefore>放入砝码</template>
                            <template #addonAfter>克</template>
                        </a-input>
                    </div>
                    <div v-show="current == 4">
                        <a-form-item>
                            <a-button size="large" type="primary" @click="writeFamar">
                                写入砝码值（{{famar}}）
                            </a-button>
                        </a-form-item>
                    </div>
                </a-col>
                <a-col :span="8" style="text-align: right;">
                    <a-button size="large" @click="next" :disabled="current == steps.length - 1">
                        <right-outlined />
                    </a-button>            
                </a-col>
                          
            </a-row>
        </div>

        <a-row type="flex">
            <a-col :span="6">
                <a-form-item label="自动读取">
                    <a-switch v-model:checked="autoread" checked-children="开" un-checked-children="关" />
                </a-form-item>
            </a-col>
            <a-col :span="4">
                <a-button type="text" @click="clear">清空</a-button>
            </a-col>
            <a-col :span="4" :offset="2">
                <a-form-item label="站号">{{ station }}</a-form-item>
            </a-col>
            <a-col :span="4">
                <a-form-item label="数据">
                    <b>{{ weight }}</b>
                </a-form-item>
            </a-col>
            <a-col :span="4">
                <a-button @click="peeling">去皮</a-button>
            </a-col>
        </a-row>
        <a-row type="flex">
            <a-col :span="10">
                <div v-if="result.length != 0" style="height: 200px;overflow-y: auto;">
                    <div v-for="(item,key) in result" :key="key">
                        <span v-if="item.event == 'send'">发：</span>
                        <span v-else style="color: red;">收：</span>
                        <span class="code">
                            <b v-for="(char, index) in item.data" :key="index">
                                <template v-if="index%2 === 0">
                                    {{ char }}{{ item.data[index+1] }}
                                </template>
                            </b>
                        </span>
                    </div>
                </div>
            </a-col>
        </a-row>

    </div>
</template>

<script>
// AD值重置 1：1 *重新上电
    // 12:50:51.431→发 02 10 00 64 00 02 04 3F 80 00 00 F6 CC 
    // 12:50:51.741←收 02 10 00 64 00 02 00 24 
    // 12:50:51.756→发 02 03 00 64 00 02 85 E7 
    // 12:50:52.065←收 02 03 04 3F 80 00 00 C4 CF 

// 零点校准
    // 13:05:29.154→发 02 06 00 35 00 01 58 37 
    // 13:05:29.466←收 02 06 00 35 00 01 58 37 
    // 13:05:29.481→发 02 03 00 35 00 01 94 37 
    // 13:05:29.791←收 02 03 02 00 01 3D 84 

// 去皮
    // 21:25:02.127→发 02 06 00 34 00 01 09 F7 
    // 21:25:02.438←收 02 06 00 34 00 01 09 F7 
    // 21:25:02.453→发 02 03 00 34 00 01 C5 F7 
    // 21:25:02.764←收 02 03 02 00 01 3D 84     

import { ipc } from '@/utils/ipcRenderer'
import { bytesToHexString, crc16Hex, divideToFloat32Hex, numberToHex, delay } from '@/utils/common'
export default {
    data() {
        return {
            current: 0, // 当前步骤
            station: 1, // 站号
            famar: 1,   // 砝码值
            ad: 1, // AD值
            autoread: false, // 自动读取
            steps: [
                { title: '步骤一', description: '站号设置' },
                { title: '步骤二', description: 'AD值重置' },
                { title: '步骤三', description: '零点校准' },
                { title: '步骤四', description: '放入砝码' },
                { title: '步骤五', description: '写入砝码' },
            ],
            result: [],
            weight: '',
            readTimer: null,
            loading: false
        }
    },
    watch: {
        autoread (val) {
            if (val) {
                this.readData()
            } else {
                this.stopReadData()
            }
        }
    },
    mounted() {
        this.ipcOn()
    },
    unmounted() {
        ipc.removeAllListeners('ipcMain')
        this.stopReadData()
    },
    methods: {
        ipcOn() {
            ipc.on('ipcMain', (event, args) => {
                console.log('ipcMain', event, args)
                if (args.channel == 'send') {
                    // this.result.unshift({ event: 'send', data: args.data })
                    this.pushData(args.data, 'send')
                }
                if (args.channel == 'receive') {
                    // this.result.unshift({ event: 'receive', data: args.data })
                    this.pushData(args.data, 'receive')
                    this.weight = this.parseWeight(args.data)
                }
            })
        },
        pushData (data, state) {
            if (this.result.length > 10) {
              this.result.splice(this.result.length -1)
            }
            this.result.unshift({ event: state, data })
        },
        next () { 
            this.readDataOnce()
            this.current += 1
        },
        prev () { 
            this.current -= 1
        },

        // AD值重置
        async ADreset () {
            // ad值重置
            // 砝码值除以ad值的数以32位浮点数形式写入
            let val = divideToFloat32Hex(1, 1)
            let address = numberToHex(this.station)
            let cmd1 = this.crc(address + '10 00 64 00 02 04 ' + val)
            let cmd2 = this.crc(address + '03 00 64 00 02')
            await this.send(cmd1)
            await delay(500)
            await this.send(cmd2)
            alert('AD值重置成功, 掉电后生效')
        },
        // 零点校准
        async zeroPoint () {
            // 02 06 00 35 00 01, // 02 03 00 35 00 01  
            this.loading = true
            let address = numberToHex(this.station)
            let value1 = this.crc(address + '06 00 35 00 01')
            await this.send(value1)
            let value2 = this.crc(address + '03 00 35 00 01')
            await delay(500)
            let res = await this.send(value2)
            if (!res.status) {
                this.$message.error('零点校准失败')
                return
            }
            this.$message.success('零点校准成功')
        },
        // 写入砝码
        async writeFamar() {
            let weight =  this.weight
            let famar = this.famar
            // 砝码值除以ad值的数以32位浮点数形式写入
            // 02 10 00 64 00 02 04 3F 80 00 00 F6 CC    
            let val = divideToFloat32Hex(famar, weight)
            let address = numberToHex(this.station)
            let cmd1 = this.crc(address + '10 00 64 00 02 04 ' + val)
            let cmd2 = this.crc(address + '03 00 64 00 02')
            await this.send(cmd1)
            await delay(500)
            await this.send(cmd2)
            alert('砝码写入成功，掉电后生效')
        },
        crc (hexString) {
            let cmd = hexString.replace(/\s/g, '');
            let crc = bytesToHexString(crc16Hex(cmd));
            return cmd + crc 
        },
        readData () {
            let address = numberToHex(this.station)
            let cmd = address + '03 00 00 00 02';
            let value = this.crc(cmd)
            this.readTimer = setInterval(() => { 
                this.send(value);
            }, 500)
        },
        async readDataOnce () { 
            let address = numberToHex(this.station)
            let cmd = address + '03 00 00 00 02';
            let value = this.crc(cmd)
            await this.send(value);
        },
        stopReadData () {
            this.autoread = false 
            clearInterval(this.readTimer)
        },
        // 发送自定义指令
        send (value) {
            // this.result.unshift({ event: 'send', data: value })    
            this.pushData(value, 'send')        
            return ipc.invoke('controller.modbusRTU.send', { value })
        },
        // 解析重量值
        parseWeight (hexString) {
            if (hexString.length != 18) {
                return ''
            }
            // 获取首位地址
            let address = parseInt(hexString.substr(0, 2), 16)
            // 获取指令（03）
            let cmd = parseInt(hexString.substr(2, 2))
            if (address != this.station || cmd != 3) {
                return ''
            }
            let hex = hexString.substr(6, 8)
            console.log('hex', hex)
            return parseInt(hex, 16)
        },
        clear () {
            this.result = []
        },
        // 去皮
        async peeling () { 
            let address = numberToHex(this.station)
            let value1 = this.crc(address + '06 00 34 00 01')
            await this.send(value1)
            let value2 = this.crc(address + '03 00 34 00 01')
            await delay(500)
            let res = await this.send(value2)
            if (!res.status) {
                this.$message.error('去皮失败')
                return
            }
            this.$message.success('去皮成功')
        },
    }
}
</script>

<style scoped>
.steps-content {
  margin-top: 16px;
  margin-bottom: 16px;
  padding: 0 6px;
  border: 1px dashed #e9e9e9;
  border-radius: 6px;
  background-color: #fafafa;
  min-height: 200px;
  text-align: center;
  color: #333;
  justify-content: space-around;
  align-items: center;
  display: flex;
  flex-direction: column;
}

.code > b{
    margin-right: 4px;
}
</style>